package rhc.taskSchedule.task.impl;

import java.util.Date;
import java.util.List;

import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import rhc.taskSchedule.SingleInstanceComponent;
import rhc.taskSchedule.entity.TaskType;
import rhc.taskSchedule.exception.NormalException;
import rhc.taskSchedule.task.ScheduleTaskTypeInnerService;

@Service
public class ScheduleTaskTypeInnerServiceImpl extends SingleInstanceComponent implements ScheduleTaskTypeInnerService {

	@Override
	public TaskType createScheduleTaskType(String taskTypeName, List<String> runNodeLabelList) throws Exception {
		TaskType taskType=getScheduleTaskTypeByName(taskTypeName);
		if(null != taskType){
			throw new NormalException("调度任务类型 {} 已存在",taskTypeName);
		}
		
		taskType=_createTask(taskTypeName,runNodeLabelList);
		return taskType;
	}

	@Override
	public TaskType updateScheduleTaskType(String taskTypeId, String taskTypeName, List<String> runNodeLabelList)
			throws Exception {
		Query query=new Query(Criteria.where(TaskType.COLUMN_ID).is(taskTypeId));
		Update update=new Update();
		update.set(TaskType.COLUMN_TASK_TYPE_NAME, taskTypeName);
		update.set(TaskType.COLUMN_RUN_NODE_LABEL, runNodeLabelList);
		
		superDao.updateFirst(query, update, TaskType.class);
		TaskType taskType=superDao.getOneT(query, TaskType.class);
		return taskType;
	}

	@Override
	public TaskType getScheduleTaskTypeByName(String taskTypeName) throws Exception {
		Query query=new Query(Criteria.where(TaskType.COLUMN_TASK_TYPE_NAME).is(taskTypeName));
		
		TaskType taskType=superDao.getOneT(query, TaskType.class);
		return taskType;
	}

	@Override
	public TaskType createOrGetScheduleTaskType(String taskTypeName, List<String> runNodeLabelList) throws Exception {
		
		TaskType taskType=getScheduleTaskTypeByName(taskTypeName);
		if(null != taskType){
			return taskType;
		}
		taskType=_createTask(taskTypeName,runNodeLabelList);
		return taskType;
	}
	
	/**创建一个任务类型
	 * @param taskTypeName
	 * @param runNodeLabelList
	 * @return
	 */
	private TaskType _createTask(String taskTypeName,List<String> runNodeLabelList){
		TaskType taskType=new TaskType();
		taskType.setCreateDate(new Date());
		taskType.setRunNodeLabel(runNodeLabelList);
		taskType.setTaskTypeName(taskTypeName);
		
		superDao.addOneT(taskType);
		return taskType;
	}

}
